package com.ltt.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ltt.annotation.NoAuth;
import com.ltt.common.UserThreadLocal;
import com.ltt.dao.pojo.User;
import com.ltt.dao.vo.Result;
import com.ltt.mapper.UserInfoMapper;
import com.ltt.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.List;

/**
 * @author ‘李天泰’
 * @version 1.0
 * @description: TODO
 * @date 2023/5/3 21:01
 */
@CrossOrigin
@Api(tags = "用户信息模块")
@RestController
@RequestMapping("/user")
public class UserInfoController {
    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @ApiOperation("更新用户头像")
    @PostMapping("/setPic")
    private Result setPic(String url) {
        User user = userInfoService.findUserById(UserThreadLocal.get().getOpenid());
        user.setUserPic(url);
        user.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        userInfoService.setPic(user);
        return Result.successWithoutData();
    }

    @ApiOperation("更新用户昵称")
    @PostMapping("/setNickName")
    private Result setNickName(String nickName) {
        User user = userInfoService.findUserById(UserThreadLocal.get().getOpenid());
        user.setNickName(nickName);
        user.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        userInfoService.setNickName(user);
        return Result.successWithoutData();
    }

    @ApiOperation("通过openid查找用户信息")
    @PostMapping("/findUserById")
    @NoAuth
    private Result findUserById(@RequestBody String openid){
        JSONObject jsonObject =  JSON.parseObject(openid);
        System.out.println(jsonObject.getString("openid"));
        User userById = userInfoService.findUserById(jsonObject.getString("openid"));
        return Result.successWithData(userById);
    }


    @ApiOperation("通过Name查找用户信息")
    @PostMapping("/findUserByName")
    @NoAuth
    private Result findUserByName(@RequestBody String name){
        JSONObject jsonObject =  JSON.parseObject(name);
        System.out.println(jsonObject.getString("name"));
        List<User> userById = userInfoMapper.findUserByName(jsonObject.getString("name"));
        return Result.successWithData(userById);
    }

    @ApiOperation("获取所有人")
    @PostMapping("/GetAll")
    @NoAuth
    private Result findUserAll(){
        List<User> users = userInfoMapper.findUserAll();
        return Result.successWithData(users);
    }
}
